import Types from '../types'
import DataStore, { FLAG_STORE } from '../../expand/dao/DataStore'
import { handleData } from '../ActionUtil'

// 获取最热数据的异步action
export function onLoadTrendingData(storeName, url, pageSize) {
    return dispatch => {
        dispatch({ type: Types.TRENDING_REFRESH, storeName });
        let dataStore = new DataStore();
        dataStore.fetchData(url, FLAG_STORE.flag_trending)
            .then(data => {
                handleData(Types.TRENDING_REFRESH_SUCCESS, dispatch, storeName, data, pageSize);
            }).catch(error => {
                console.log(error);
                dispatch({ type: Types.POPULAR_REFRESH_FAIL, storeName, error });
            }); // 异步action与数据流
    };
}
// 加载更多
export function onLoadMoreTrending(storeName, pageIndex, pageSize, dataArray = [], callback) {
    return dispatch => {
        setTimeout(() => { // 模拟网络请求
            if ((pageIndex - 1) * pageSize >= dataArray.length) { // 已加载完全部数据
                if (typeof callback === 'function') {
                    callback('no more');
                }
                dispatch({
                    type: Types.TRENDING_LOAD_MORE_FAIL,
                    error: 'no more',
                    storeName,
                    pageIndex: --pageIndex,
                    projectModel: dataArray,
                })
            } else {
                // 本次可载入的最大数量
                let max = pageSize * pageIndex > dataArray.length ? dataArray.length : pageSize * pageIndex;
                dispatch({
                    type: Types.TRENDING_LOAD_MORE_SUCCESS,
                    storeName,
                    pageIndex,
                    projectModel: dataArray.slice(0, max),
                })
            }
        }, 500)
    }
}